import 'dart:io';


import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'package:flutter_chat_bubble/bubble_type.dart';
import 'package:flutter_chat_bubble/chat_bubble.dart';
import 'package:flutter_chat_bubble/clippers/chat_bubble_clipper_4.dart';

import 'package:image_picker/image_picker.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import '../../common/colors.dart';
import '../../utils/hexcolor.dart';


class MessageModel{
  bool? isSelf;
  String? messageData;
  String? type;
  MessageModel(this.isSelf,this.messageData,this.type);
}
class AppLifecycleReactor extends StatefulWidget {

  @override
  State<AppLifecycleReactor> createState() => _AppLifecycleReactorState();
}

class _AppLifecycleReactorState extends State<AppLifecycleReactor> with WidgetsBindingObserver {
  // 输入框的焦点实例
  FocusNode? _focusNode;
  // 当前键盘是否是激活状态


  var messageArr = [];

  final TextEditingController _messageTextTF = TextEditingController();

  final ScrollController _scrollController = ScrollController();

  bool isShowKeybordy = false;
  bool isShowEmoji = false;

  var height = 0.0;

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();

    // 创建一个界面变化的观察者
    WidgetsBinding.instance.addObserver(this);

    // _focusNode!.addListener(_onFocus);
  }
  sendText(String text,var type){
    if(text==''){
      return;
    }

    messageArr.add(MessageModel(true, text,'${type}'));
    setState(() {
      Future.delayed(Duration(milliseconds: 100), () {
        _scrollController.animateTo(_scrollController.position.maxScrollExtent+15,
            duration: Duration(milliseconds: 200), curve: Curves.ease);
      });
      _messageTextTF.text = '';
    });
  }
  Widget _richtext(){
    return RichText(text: TextSpan(
      children: [
        WidgetSpan(child: Image.asset('images/expression/aoman1.png'))
      ]
    ));
  }
  // 焦点变化时触发的函数
  _onFocus() {
    if (_focusNode!.hasFocus) {

      // 聚焦时候的操作
      // height =  285.0;
      print('成为焦点${height}');
      isShowEmoji = false;
      Future.delayed(Duration(milliseconds: 1), () {
        _scrollController.animateTo(_scrollController.position.maxScrollExtent+4,
            duration: Duration(milliseconds: 1), curve: Curves.ease);
      });
    }else{
      height  = MediaQuery.of(context).viewInsets.bottom;
      print('失去焦点${height}');

    }
    setState(() {

    });
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();

    print('didChangeMetrics${MediaQuery.of(context).viewInsets.bottom}');

    // if(MediaQuery.of(context).viewInsets.bottom==0){
    //   _scrollController.animateTo(_scrollController.position.maxScrollExtent,
    //       duration: Duration(microseconds: 2000), curve: Curves.linear);
    //   print('0 = ${MediaQuery.of(context).viewInsets.bottom}');
    //
    //   if(isShowEmoji ==true){
    //     isShowEmoji = false;
    //   }
    //
    //   return;
    //
    // }else{
    //   if(isShowEmoji==true){
    //
    //     isShowEmoji = false;
    //     setState(() {
    //
    //     });
    //     return;
    //   }
    //
    //   print('1 = ${MediaQuery.of(context).viewInsets.bottom}');
    //
    // }

    setState(() {

    });
  }



  @override
  void dispose() {
    _focusNode!.dispose();
    WidgetsBinding.instance!.removeObserver(this);
    super.dispose();
  }

  AppLifecycleState? _notification;
  int i = 0;
  @override

  void didChangeAppLifecycleState(AppLifecycleState state) {
    // TODO: implement didChangeAppLifecycleState
    super.didChangeAppLifecycleState(state);
    switch (state) {
    //进入应用时候不会触发该状态 应用程序处于可见状态，并且可以响应用户的输入事件。它相当于 Android 中Activity的onResume
      case AppLifecycleState.resumed:
        print("应用进入前台======");
        i++;
        setState(() {

        });
        break;
    //应用状态处于闲置状态，并且没有用户的输入事件，
    // 注意：这个状态切换到 前后台 会触发，所以流程应该是先冻结窗口，然后停止UI
      case AppLifecycleState.inactive:
        print("应用处于闲置状态，这种状态的应用应该假设他们可能在任何时候暂停 切换到后台会触发======");
        break;
    //当前页面即将退出
      case AppLifecycleState.detached:
        print("当前页面即将退出======");
        break;
    // 应用程序处于不可见状态
      case AppLifecycleState.paused:
        print("应用处于不可见状态 后台======");
        break;
    }
  }



  @override

  Widget build(BuildContext context) {

    print('build === ${MediaQuery.of(context).viewInsets.bottom}');

    return Scaffold(
      backgroundColor: Colors.white,
        resizeToAvoidBottomInset: false, // 解决键盘顶起页面
        appBar: AppBar(
          elevation: 0,
          title: Text('聊天',style: TextStyle(color: Colors.black87),),
        ),
        body: SafeArea(
          child: GestureDetector(
            onTap:(){
              height = 0;
              _focusNode!.unfocus();

            },
            child: Stack(
              children: [
                Container(
                  color: HexColor('#EEEEEE'),
                  margin: EdgeInsets.only(bottom:isShowEmoji==true?150+50:MediaQuery.of(context).viewInsets.bottom+50),
                  child:EasyRefresh.custom(
                    scrollController: _scrollController,

                    slivers: [
                      SliverList(delegate: SliverChildBuilderDelegate((context,index){
                        if(index%2==0){
                          return MessageCell(true,messageArr[index]);
                        }
                        return MessageCell(false,messageArr[index]);
                      },childCount:messageArr.length ))
                    ],),
                ),

                Positioned(
                  bottom:0,
                  child:Align(
                  alignment: Alignment.bottomCenter,
                  child:Column(
                    children: [
                      Container(
                        padding: EdgeInsets.only(left: 10),
                        color: Colors.white,
                        height: 50,
                        width: Get.width,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            GestureDetector(
                              onTap: (){
                                setState(() {

                                });
                              },
                              child: Container(
                                width: 25,
                                height: 25,
                                child: Image.asset('images/zan.png'),
                              ),
                            ),

                            GestureDetector(
                              onTap: (){
                                setState(() {

                                  isShowEmoji =! isShowEmoji;

                                  if(isShowEmoji){
                                    height = 260;
                                    _focusNode!.unfocus();

                                  }else{
                                    height = 0;
                                    _focusNode!.nextFocus();
                                  }
                                  // Future.delayed(Duration(milliseconds: 1), () {
                                  //   _scrollController.animateTo(_scrollController.position.maxScrollExtent,
                                  //       duration: Duration(milliseconds: 1), curve: Curves.linear);
                                  // });

                                });
                              },
                              child: Container(
                                width: 25,
                                height: 25,
                                child: Image.asset('images/chat_add.png'),
                              ),
                            ),
                            // IconButton(onPressed: (){
                            //   setState(() {
                            //     _focusNode!.unfocus();
                            //     isShowEmoji = true;
                            //     height = 285;
                            //     print('2222');
                            //   });
                            // }, icon: Image.asset('images/chat_add.jpg')),
                            Container(
                              padding: EdgeInsets.only(left: 15,right: 5),
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  color: Colors.grey[200],
                                  borderRadius: BorderRadius.all(Radius.circular(18))
                              ),
                              width: Get.width-150,
                              height: 35,
                              child:  TextField(
                                decoration: const InputDecoration(
                                  hintText: '请输入的内容',
                                  isCollapsed: true,
                                  border: InputBorder.none,
                                ),
                                onSubmitted: (s){
                                  sendText(s,'text');
                                  setState(() {

                                  });
                                  print(s);
                                },
                                textInputAction:TextInputAction.send ,
                                controller: _messageTextTF,
                                focusNode: _focusNode,
                              ),
                            ),
                            TextButton(onPressed: (){
                              sendText(_messageTextTF.text,'text');
                            }, child:Text('发送',style: TextStyle(color: Colors.black54
                            ,fontSize: 13),))
                          ],
                        ),
                      ),
                      // Emoji(height,),
                      Emoji(MediaQuery.of(context).viewInsets.bottom, (path) {
                        sendText(path,'picture');
                      },isShowEmoji)
                    ],
                  ),
                ),)
              ],
            ),
          ),
        )
    );
  }
}

class MessageCell extends StatefulWidget {

  late bool isSelf;
  late MessageModel message;

  MessageCell(this.isSelf,this.message);

  @override
  State<MessageCell> createState() => _MessageInfoState();
}

class _MessageInfoState extends State<MessageCell> {

  @override
  Widget build(BuildContext context) {
    if(widget.isSelf){
      if(widget.message.type == 'text'){
        return Container(
          margin: EdgeInsets.only(left: 15,top: 15,right: 15,bottom: 10),
          alignment: Alignment.centerRight,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              ChatBubble(
                elevation: 0,
                clipper: ChatBubbleClipper4(type: BubbleType.sendBubble),
                alignment: Alignment.topRight,
                margin: EdgeInsets.only(top: 0),
                backGroundColor: Theme.of(context).primaryColor,
                child: Container(
                  constraints: BoxConstraints(
                    maxWidth: MediaQuery.of(context).size.width * 0.7,
                  ),
                  child: Text(
                    '${widget.message.messageData}',
                    style: TextStyle(color: AppColor.textColor,fontSize: 16,
                    fontWeight: FontWeight.w500
                    ),
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: 5),
                clipBehavior: Clip.hardEdge,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(3))
                ),
                child: Image.asset('images/alipy.png',fit: BoxFit.cover,),
                width: 35,
                height: 35,
              ),
            ],
          ),
          // color: Colors.red,
        );
      }else if(widget.message.type == 'picture'){
        return Container(
          margin: EdgeInsets.only(left: 15,top: 15,right: 15,bottom: 10),
          alignment: Alignment.centerRight,
          child: Container(
            constraints: BoxConstraints(
              maxWidth: MediaQuery.of(context).size.width * 0.8,
            ),
            child:Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Image.file(File(widget.message.messageData!),scale: 15,),
                Container(
                  margin: EdgeInsets.only(left: 5),
                  clipBehavior: Clip.hardEdge,
                  decoration: const BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(3))
                  ),
                  child: Image.asset('images/alipy.png',fit: BoxFit.cover,),
                  width: 35,
                  height: 35,
                ),
              ],
            ),
          ),
          // color: Colors.red,
        );
      }
    }
    return Container(
      // color:Colors.red,
      margin: EdgeInsets.all(15),
      // height: 100,
      width: Get.width,

      child: Column(
        children: [
          4%2==0?
          Container(
            color:Colors.white,
            padding: EdgeInsets.all(3),
            child: Text('2022年04月19日 19:26',style: TextStyle(fontSize: 12
                ,color:AppColor.smallTextColor),),
          ):Container(),
          ChatBubble(
            elevation: 0,
            clipper: ChatBubbleClipper4(type: BubbleType.receiverBubble),
            alignment: Alignment.topLeft,
            margin: EdgeInsets.only(top: 20),
            backGroundColor: Colors.white,
            child: Container(
              constraints: BoxConstraints(
                maxWidth: MediaQuery.of(context).size.width * 0.7,
              ),
              child: Text(
                "我是何四薪，你可以叫我double薪！嘿嘿！",
                style: TextStyle(color: AppColor.textColor,fontSize: 16,
                    fontWeight: FontWeight.w500),
              ),
            ),
          ),

        ],
      ),
      // color: Colors.yellowAccent,
    );
  }
}

typedef _EmojiCallBack = void Function(String path);

class Emoji extends StatefulWidget {


  final _EmojiCallBack emojiCallBack;

  var height;

  bool isShowEmoji;

  Emoji(this.height, this.emojiCallBack,this.isShowEmoji);

  @override
  State<Emoji> createState() => _EmojiState();
}

class _EmojiState extends State<Emoji> {


  final ImagePicker _picker = ImagePicker();

   selectImage()async{
     // Pick an image
     final XFile? image = await _picker.pickImage(source: ImageSource.gallery,imageQuality: 30);
     print(image!.path);
     widget.emojiCallBack(image.path);
   }

  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      padding: EdgeInsets.only(left: 15,top: 15),
      height:widget.isShowEmoji==true?150:widget.height,
      width: Get.width,
      color: Colors.white, duration: Duration(milliseconds:215 ),
      curve: Curves.ease,
      child:
      // EmoJiPage2((path){
      //   print(path);
      // }),
      Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Opacity(
            opacity:widget.isShowEmoji==true?1:0,
            child: GestureDetector(
              onTap: ()async{
                selectImage();
              },
              child: Container(
                // color: Colors.red,
                width: 60,
                height: 100,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Image.asset('images/picture.png'),
                    Text('发送图片',style: TextStyle(color: Colors.grey),)
                  ],
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}


